<template>
  <div class="key-list-container">
    <el-container>
      <el-header class="header">
        <div class="header-left">
          <span class="logo">卡密管理系统</span>
        </div>
        <div class="header-right">
          <el-dropdown trigger="click">
            <span class="user-info">
              <User class="user-icon" />
              <span>管理员</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      <el-container>
        <el-aside width="200px" class="sidebar">
          <el-menu :default-openeds="['2']" router>
            <el-sub-menu index="1">
              <template #title>
                <DashboardIcon class="menu-icon" />
                <span>仪表盘</span>
              </template>
              <el-menu-item index="/dashboard">
                <span>数据统计</span>
              </el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="2">
              <template #title>
                <Key class="menu-icon" />
                <span>卡密管理</span>
              </template>
              <el-menu-item index="/generate">
                <span>生成卡密</span>
              </el-menu-item>
              <el-menu-item index="/keys">
                <span>卡密列表</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>
        <el-main class="main-content">
          <el-card class="filter-card">
            <el-form :model="filterForm" class="filter-form" inline>
              <el-form-item label="应用筛选">
                <el-select v-model="filterForm.appId" placeholder="所有应用" @change="handleFilter" default-first-option style="width: 180px;">
                  <el-option value="" label="所有应用" />
                  <el-option v-for="app in apps" :key="app.id" :label="app.name" :value="app.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="状态筛选">
                <el-select v-model="filterForm.status" placeholder="所有状态" @change="handleFilter" default-first-option style="width: 180px;">
                  <el-option value="" label="所有状态" />
                  <el-option value="activated" label="已激活" />
                  <el-option value="unactivated" label="未激活" />
                  <el-option value="expired" label="已过期" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="resetFilters">重置筛选</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="navigateToGenerate">生成新卡密</el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <el-card class="keys-table-card">
            <template #header>
              <div class="card-header">
                <span>卡密列表</span>
              </div>
            </template>
            <el-table :data="cardKeys" style="width: 100%">
              <el-table-column prop="key" label="卡密" width="180">
                <template #default="scope">
                  <div class="key-tooltip" :title="scope.row.key">{{ scope.row.key }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="app_name" label="应用名" width="120" />
              <el-table-column label="卡类型" width="100">
                <template #default="scope">
                  {{ getCardType(scope.row.valid_days) }}
                </template>
              </el-table-column>
              <el-table-column prop="activation_time" label="激活日期" width="150" />
              <el-table-column prop="expires_at" label="有效期至" width="150" />
              <el-table-column prop="status_text" label="状态" width="80" />
              <el-table-column label="操作" width="140">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="viewKeyDetail(scope.row.id)">
                    详情
                  </el-button>
                  <el-button type="danger" size="small" @click="deleteKey(scope.row.id)" style="margin-left: 10px;">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container" v-if="total > 0">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
            <div v-else class="no-data">暂无数据</div>
          </el-card>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { User, DashboardIcon, Key } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const cardKeys = ref([])
const apps = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const filterForm = ref({
  appId: '',
  status: ''
})

// 加载应用列表
const loadApps = async () => {
  try {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (!token) {
      router.push('/login')
      return
    }

    // 调用后端API获取应用列表
    const response = await axios.get('/api/apps', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.data.success) {
      apps.value = response.data.data
    } else {
      ElMessage.error(response.data.message || '加载应用列表失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
    console.error('Failed to load apps:', error)
  }
}

// 加载卡密列表
const loadCardKeys = async () => {
  try {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (!token) {
      router.push('/login')
      return
    }

    // 调用后端API获取卡密列表
    const response = await axios.get('/api/keys', {
      params: {
        appId: filterForm.value.appId,
        status: filterForm.value.status,
        page: currentPage.value,
        pageSize: pageSize.value
      },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.data.success) {
      cardKeys.value = response.data.data.items
      console.log('卡密数据:', cardKeys.value)
      total.value = response.data.data.total
    } else {
      ElMessage.error(response.data.message || '加载卡密列表失败')
      cardKeys.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
    console.error('Failed to load card keys:', error)
    cardKeys.value = []
    total.value = 0
  }
}

// 处理筛选
const handleFilter = () => {
  console.log('筛选参数:', filterForm.value);
  currentPage.value = 1
  loadCardKeys()
}

// 重置筛选
const resetFilters = () => {
  filterForm.value = {
    appId: '',
    status: ''
  }
  currentPage.value = 1
  loadCardKeys()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadCardKeys()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  loadCardKeys()
}

// 查看卡密详情
const viewKeyDetail = (id) => {
  router.push(`/keys/${id}`)
}

// 获取卡类型
const getCardType = (validDays) => {
  if (validDays === 0) return '永久卡'
  if (validDays === 1) return '日卡'
  if (validDays === 7) return '周卡'
  if (validDays === 30) return '月卡'
  if (validDays === 90) return '季卡'
  if (validDays === 180) return '半年卡'
  if (validDays === 365) return '年卡'
  return '自定义'
}

// 删除卡密
const deleteKey = async (id) => {
  try {
    // 弹出确认对话框
    const result = await ElMessageBox.confirm(
      '确定要删除此卡密吗？此操作不可撤销。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (result === 'confirm') {
      // 从localStorage获取token
      const token = localStorage.getItem('token')
      if (!token) {
        router.push('/login')
        return
      }

      // 调用后端API删除卡密
      const response = await axios.delete(`/api/keys/${id}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (response.data.success) {
        ElMessage.success('删除成功')
        // 刷新卡密列表
        loadCardKeys()
      } else {
        ElMessage.error(response.data.message || '删除失败')
      }
    }
  } catch (error) {
    if (error === 'cancel') {
      return
    }
    ElMessage.error('网络错误，请稍后重试')
    console.error('Failed to delete key:', error)
  }
}

// 跳转到生成卡密页面
const navigateToGenerate = () => {
  router.push('/generate')
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('token')
  ElMessage.success('退出成功')
  router.push('/login')
}

onMounted(() => {
  // 检查URL参数中的筛选条件
  if (route.query.appId) {
    filterForm.value.appId = route.query.appId
  }
  loadApps()
  loadCardKeys()
})
</script>

<style scoped>
.key-list-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.header {
  background-color: #409eff;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
}
.logo {
  font-size: 20px;
  font-weight: bold;
}
.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}
.user-icon {
  margin-right: 5px;
}
.sidebar {
  background-color: #f0f2f5;
  padding-top: 20px;
}
.menu-icon {
  margin-right: 10px;
}
.main-content {
  padding: 20px;
  background-color: #f5f7fa;
  overflow-y: auto;
  flex: 1;
}
.filter-card {
  margin-bottom: 20px;
}
.filter-form {
  width: 100%;
}
.card-header {
  font-size: 16px;
  font-weight: bold;
}
.keys-table-card {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.no-data {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.key-tooltip {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
}
</style>